package com.yonyou.iuap.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springside.modules.security.utils.Digests;
import org.springside.modules.utils.Encodes;

import com.yonyou.iuap.auth.shiro.AuthConstants;
import com.yonyou.iuap.auth.token.ITokenProcessor;
import com.yonyou.iuap.auth.token.TokenParameter;
import com.yonyou.iuap.base.intf.IUserAdminService;
import com.yonyou.iuap.base.vo.UserVO;
import com.yonyou.iuap.cache.CacheManager;
import com.yonyou.iuap.shell.pub.ResultDto;

@Controller
@RequestMapping(value="/login")
public class ShellLoginController {
	private Logger LOGGER = Logger.getLogger(getClass());
	public static final int HASH_INTERATIONS = 1024;
	@Autowired
	private CacheManager cacheManager;
	@Autowired
	private IUserAdminService iuser;
	@Autowired()
	protected ITokenProcessor webTokenProcessor;
	
	
	@RequestMapping(method = RequestMethod.GET)
	public String login(Model model) {
		return "login";
	}
	@RequestMapping("/formLogin")
	public String formLogin(HttpServletRequest request,HttpServletResponse response,Model model){
		
		ResultDto rsDto = new ResultDto();
		/**
		 * 注意，此示例中简单验证了用户的登录过程，正规上线环境，需要考虑
		 * 前端用ras算法加密，此处用iuap-security组件中的RsaUtils解密，前端需要做输入校验
		 */
		String user_code = request.getParameter("username");
		String user_pwd = request.getParameter("password");
		//查询用户信息
		UserVO uservo = getUserVOByName(user_code);
		if(StringUtils.isEmpty(user_pwd) || StringUtils.isEmpty(user_pwd)){
			rsDto.setStatus(-1);
			rsDto.setMessage("用户名或者密码不能为空!");
			model.addAttribute("accounterror", rsDto);
			return "login";
		}
		if(uservo==null){
			rsDto.setStatus(-1);
			rsDto.setMessage("用户不存在!");
			model.addAttribute("accounterror", rsDto);
			return "login";
		}else{
			byte[] hashPassword = Digests.sha1(user_pwd.getBytes(), Encodes.decodeHex("7efbd59d9741d34f"), HASH_INTERATIONS);
			String checkPwd = Encodes.encodeHex(hashPassword);
			if(!checkPwd.equals(uservo.getPassword())){
                
                TokenParameter tp = new TokenParameter();
                tp.setUserid(user_code);
                // 设置登录时间
                tp.setLogints(String.valueOf(System.currentTimeMillis()));
                // 租户信息,saas应用登录的时候获取用户信息，设置租户id
                tp.getExt().put(AuthConstants.PARAM_TENANTID , "test_tenant_id");
                
                Cookie[] cookies = webTokenProcessor.getCookieFromTokenParameter(tp);
                for(Cookie cookie : cookies){
            	   response.addCookie(cookie);
                }
            } else {
            	rsDto.setStatus(-1);
            	rsDto.setMessage("用户密码错误!");
                model.addAttribute("accounterror", rsDto);
                return "login";
            }
            return "redirect";
		}
		
	}
	@RequestMapping(method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
		return "login";
	}
	private UserVO getUserVOByName(String name){
		try {
			UserVO user = iuser.selectByCondition(" user_name='"+name+"' or user_code='"+name+"'");
			return user;
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return null;
		}
	}
}
